//
//  PullDownRefreshControll.swift
//  NSinaWeibo
//
//  Created by LoliQueen on 16/2/24.
//  Copyright © 2016年 LoliQueen. All rights reserved.
//

import UIKit
///设置刷新状态
enum refreshStatue : Int {
    case Normal = 1
    case Pulling = 2
    case Refreshing = 3
}

class PullDownRefreshControll: UIControl {
   
    
    //记录父视图
    var scrollView : UIScrollView?
    //记录上次刷新的状态
//    var lastStatue : refreshStatue = .Normal
    //声明状态属性 默认是正常状态
    var Pullstatue: refreshStatue = .Normal{
        didSet{
            switch Pullstatue {
            case .Normal:
                tipLabel.text = "下拉刷新"
                //显示箭头，停止小菊花
                arrowIcon.hidden = false
                indicationView.stopAnimating()
                //旋转箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                
                //恢复 父视图的inset  需要根据上衣的刷新状态来决定是否执行 减 inset.top的操作\
                
                //didSet 中可以去到上一次的值 oldValue。所以用不到 lastValue
                if oldValue == .Refreshing {
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        inset.top -= self.refreshHeight
                        self.scrollView?.contentInset = inset
                        
                    })
                }
                
            case .Pulling :
                tipLabel.text = "松开刷新"
                //旋转箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing :
                tipLabel.text = "正在刷新"
                //系统会主动出发这个方法
                self.sendActionsForControlEvents(.ValueChanged)
                //隐藏箭头，转动小菊花
                self.arrowIcon.hidden = true
                self.indicationView.startAnimating()
                
                //修改父视图的contentInset
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView!.contentInset
                    inset.top += self.refreshHeight
                    self.scrollView?.contentInset = inset
                    
                })
            }
            //            记录上次刷新的状态
//            lastStatue = Pullstatue
        }
        
    }
    
    let refreshHeight : CGFloat = 60
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshHeight, width: ScreenWidth, height: refreshHeight)
        super.init(frame: rect)
//        self.backgroundColor = UIColor.brownColor()
        
        setUpUI()
    }
    
    
    func endRefreshing(){
        Pullstatue = .Normal
        //延时执行,延迟返回下拉舒心状态，方便用户观察
        //从现在开始，0.3后执行
        
        ///为什么没有效果？？？？？？？
        let time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 10))
        dispatch_after(time_t, dispatch_get_main_queue()) { () -> Void in
            //闭包中，属性要加self 才能获取到
            self.Pullstatue = .Normal
        }
    }
    
    ///重写UIView生命周期
    //视图将要添加到俯视图上时
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //判断俯视图是否是UIScrollView 或UIScrollView的子视图 tabelView，collectionView
        if let superView = newSuperview as? UIScrollView{
        
            //记住父视图
            scrollView = superView
            //监控父视图tabelView的偏移位置
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
            
        }
    }
    ///移除观察者
    deinit{
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    ///KVO观察响应方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(change)
        ///比较tabelView的偏移量，和临界值的关系 60+64 = -124
        let criticalValue = -(refreshHeight + (scrollView?.contentInset.top ?? 0))
        //获得tabelView垂直方向的偏移位置
        let offsetY = scrollView?.contentOffset.y ?? 0
        
        if scrollView!.dragging{
            //tabelView正在被拖拽
            if Pullstatue == .Normal && criticalValue > offsetY {
                print("准备刷新")
                Pullstatue = .Pulling
                
            }else if Pullstatue == .Pulling && criticalValue < offsetY {
                print("下拉刷新")
                Pullstatue = .Normal
                
            }
        }else{
            //满足准备刷新的状态时松手
            if Pullstatue == .Pulling {
                print("正在刷新")
                
                Pullstatue = .Refreshing
                
            }
            
        }
    }

    
    ///添加在控件
    private func setUpUI(){
        addSubview(backImageView)
        addSubview(tipLabel)
        addSubview(arrowIcon)
        addSubview(indicationView)
        backImageView.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self)
        }
        
        //设置约束
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(15)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(tipLabel.snp_left).offset(5)
            make.centerY.equalTo(tipLabel.snp_centerY)
        }
        
        indicationView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(arrowIcon.snp_center)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
   
    
    ///懒加载子控件
    //背景图
    lazy var backImageView : UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    //提示文字
    private lazy var tipLabel: UILabel = UILabel(title: "下拉刷新", textSize: 14, textColor: UIColor.grayColor())
    
    //箭头
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //小菊花
    private lazy var indicationView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)

}
